package com.food.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.food.entity.dto.CouponWebDto;
import com.food.entity.pojo.Coupon;
import com.food.entity.vo.CouponVo;
import com.food.entity.vo.PageVo;
import com.food.mapper.CouponMapper;
import com.food.service.CouponService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements CouponService {

    @Autowired
    private CouponMapper couponMapper;

    @Override
    public List<CouponVo> getCouponsByUserId(Integer userId) {
        QueryWrapper<Coupon> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<Coupon> coupons = baseMapper.selectList(wrapper);

        return coupons.stream().map(c -> {
            CouponVo vo = new CouponVo();
            BeanUtils.copyProperties(vo, c);
//            vo.setIsActive(!c.getValidTo().isBefore(LocalDateTime.now())); // 判断是否未过期
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public PageVo<Coupon> listCoupon(CouponWebDto couponWebDto) {
        Page<Coupon> page = new Page<>(couponWebDto.getPage(), couponWebDto.getSize());
        LambdaQueryWrapper<Coupon> wrapper = new LambdaQueryWrapper<>();
        if(couponWebDto.getValidFrom() != null) {
            wrapper.ge(Coupon::getValidFrom, couponWebDto.getValidFrom());
        }
        if(couponWebDto.getValidTo() != null) {
            wrapper.le(Coupon::getValidTo, couponWebDto.getValidTo());
        }
        Page<Coupon> paged = page(page, wrapper);
        long total = paged.getTotal();
        Integer count = Integer.valueOf((int) total);
        List<Coupon> records = paged.getRecords();
        return new PageVo<>(count, records);
    }

    @Override
    public void addCoupon(Coupon coupon) {
        couponMapper.insert(coupon);
    }

    @Override
    public void updateCoupon(Coupon coupon) {
        couponMapper.updateById(coupon);
    }

    @Override
    public void deleteCoupon(Integer couponId) {
        couponMapper.deleteById(couponId);
    }
}
